package com.byx.imserverutil.netty;

import com.byx.imserverutil.entity.NettyChannel;
import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ChannelContainer
 * 存储所有通道的容器实现类
 * @author Superb
 * @date 2021/2/21 10:37
 */
public class NettyChannelContainer{
    private final Map<String, NettyChannel> CHANNELS=new ConcurrentHashMap<String, NettyChannel>();

    private static final NettyChannelContainer CONTAINER=new NettyChannelContainer();

    public static NettyChannelContainer getInstance(){
        return CONTAINER;
    }

    public void addChannel(NettyChannel nettyChannel) {
        if(nettyChannel != null){
            CHANNELS.put(nettyChannel.getUserId(),nettyChannel);
        }
    }

    public NettyChannel removeChannel(String id) {
        if(CHANNELS.containsKey(id) && !CHANNELS.get(id).isActive()){
            return CHANNELS.remove(id);
        }
        return null;
    }

    public NettyChannel getActiveChannel(String id) {
        if(CHANNELS.containsKey(id)){
            return CHANNELS.get(id);
        }
        return null;
    }

    public NettyChannel removeChannel(Channel channel){
        if(channel != null){
            for (Map.Entry<String, NettyChannel> entry : CHANNELS.entrySet()) {
                if(channel.id().toString().equals(entry.getValue().getChannelId())){
                    return removeChannel(entry.getKey());
                }
            }
        }
        return null;
    }

    public List<NettyChannel> getAll(){
        List<NettyChannel> channels=new ArrayList<NettyChannel>();
        for(Map.Entry<String, NettyChannel> entry:CHANNELS.entrySet()){
            channels.add(entry.getValue());
        }
        return channels;
    }

    public void clear(){
        CHANNELS.clear();
    }
}
